function createLeaf(id, name, level, children, parent, haveCTN) {
    var leaf = '<div id="ct_'+id+'" cat_id="'+id+'" cat_parent="'+parent+'"';
    if ( level > 2 )
        leaf += ' style="display: none"';
    leaf += '><a class="catalogTree" cat_id="'+id+'"';
    if ( children ) {
        leaf += ' children="1">';
        if ( level > 1 )
            leaf += '+';
        else
            leaf += '-';
    } else
        leaf += ' children="0" >:';
    leaf += '</a> ';
    if ( haveCTN )
        leaf += '<input class="catalogTree" type="checkbox" name="cat_'+id+'" id="cat_'+id+'_" value="'+id+'" cat_parent="'+parent+'"/>';
    else
        leaf += '<input type="checkbox" disabled />';
    leaf += '<label for="cat_'+id+'_" >'+name+'</label>';
    leaf += ' </div>';
    return leaf;
}

function createTree(tree, data, level, parent) {
    $.each(data, function(key, value) {
        // key - id category, value - categories data
        if ( value.ctn || value.children > 0 ) {
            var children = false;
            if ( value.children > 0 )
                children = true;
            tree.append(createLeaf(key, value.name, level, children, parent, value.ctn));
            if ( children )
                createTree($('#ct_'+key), value.cats, level+1, key);
        }
    });
}

function reloadTree(parentId, path) {
    ajax.jGet(urlManager.getUrl('/cm/ajax'), {'action': 'catTree', 'parentId': parentId}, function(data) {
        if ( data && data.ok == 1 ) {
            var tree = $('#categoriesTree');
            tree.empty();
            createTree(tree, data.cats, 1, 0);

            if ( path ) {
                $('#WizardStepTwoForm_category').val(0);
                $('#wiz_chuse_category').html(data.path);
                $('#categories_dlg').dialog('open');
            } else {
                var curCat = $('#WizardStepTwoForm_category').val();
                if ( curCat > 0 ) {
                    expandFor(curCat);
                    $('#cat_'+curCat+'_').attr('checked', true);
                    checkedChildren(curCat);
                    expandAll(curCat);
                }
            }
        }
    });
}

function expandAll(parentId) {
    $('div[cat_parent='+parentId+']').each(function() {
        var id = $(this).attr('cat_id');
        var anhor = $('a.catalogTree[cat_id='+id+']');
        if ( anhor && anhor.attr('children') == 1 ) {
            anhor.text('-');
            expandAll(id);
        }
        $(this).css('display', 'block');
    });
}
function expandFor(catId) {
    var div = $('div[cat_id='+catId+']');
    if ( div ) {
        var parentId = div.attr('cat_parent');
        if ( parentId > 0 ) {
            $('a.catalogTree[cat_id='+parentId+']').text('-');
            $('div[cat_parent='+parentId+']').each(function() {
                $(this).css('display', 'block');
            });
            expandFor(parentId);
        }
    }
}
function callapseAll(parentId) {
    $('div[cat_parent='+parentId+']').each(function() {
        var id = $(this).attr('cat_id');
        var anhor = $('a.catalogTree[cat_id='+id+']');
        if ( anhor && anhor.attr('children') == 1 ) {
            anhor.text('+');
            callapseAll(id);
        }
        $(this).css('display', 'none');
    });
}



function checkedChildren(parentId) {
    $('input.catalogTree[cat_parent='+parentId+']').each(function() {
        checkedChildren($(this).val());
        $(this).attr({
            'checked':          true,
            'disabled':        true,
        });
    });
}

function chuseCategory() {
    var obj = $('input.catalogTree[!disabled]:checked');
    if ( obj ) {
        $('#WizardStepTwoForm_category').val(obj.val());
        ajax.jGet(urlManager.getUrl('/cm/ajax'), {'action': 'catPath', 'catId': obj.val()}, function(data) {
            if ( data && data.ok == 1 ) {
                $('#wiz_chuse_category').html(data.path);
                $('#categories_dlg').dialog('close');
            }
        });
    }
}

(function($){
        $(document).ready(function() {

            $("input[name='WizardStepTwoForm[ad_type]']").change(function() {
                reloadTree($("input[name='WizardStepTwoForm[ad_type]']:checked").val(), true);
            });

            $('#wiz_chuse_category').bind('click', function() {
                if ($("#WizardStepTwoForm_category").val() >= 0 )
                    $('#categories_dlg').dialog('open');
            });

            $('a.catalogTree').live('click', function() {
                 var id = $(this).attr('cat_id');
                 if ( $(this).attr('children') == 1 ) {
                    // Try expand
                    if ( $(this).text() == '+' ) {
                        $(this).text('-');
                        $('div[cat_parent='+id+']').each(function() {
                            $(this).css('display', 'block');
                        });
                    } else {
                        $(this).text('+');
                        callapseAll(id);
                    }
                }
            });

            $('input.catalogTree').live('change', function() {
                var checked = $(this).is(':checked')

                $('input.catalogTree').attr({
                    'checked': false,
                    'disabled': false,
                });
                $(this).attr('checked', checked);
                if ( checked ) {
                    checkedChildren($(this).val());
                    expandAll($(this).val());
                } else {
                    $('input.catalogTree').attr('disabled', false);
                }
            });


            var curCat = $("input[name='WizardStepTwoForm[ad_type]']:checked").val();
            if ( curCat > 0 )
                reloadTree(curCat, false);

        });
})(jQuery);